package cn.ywrby.controller;

import cn.ywrby.domain.ApplyProcess;
import cn.ywrby.domain.User;
import cn.ywrby.res.ResultResponse;
import cn.ywrby.service.CommonService;
import cn.ywrby.service.UserService;
import cn.ywrby.utils.Constants;
import cn.ywrby.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 通用Controller层
 */
@RestController
@RequestMapping("/api")
public class CommonController {

    @Autowired
    UserService userService;

    @Autowired
    CommonService commonService;

    @GetMapping("/applyProcess")
    public ResultResponse getApplyProcess(@RequestHeader("authorization") String token,@RequestParam("applyId") String applyId){
        //System.out.println(token);
        ResultResponse res=new ResultResponse();
        //验证token的合法和有效性
        String tokenValue= JwtUtils.verify(token);
        System.out.println(tokenValue);
        if(tokenValue!=null && tokenValue.startsWith(JwtUtils.TOKEN_SUCCESS)){
            //如果合法则获取用户信息
            String userId=tokenValue.replaceFirst(JwtUtils.TOKEN_SUCCESS,"");

            List<ApplyProcess> applyProcessList= commonService.getApplyProcess(applyId);
            res.setData(applyProcessList);
            res.setCode(Constants.STATUS_OK);
            res.setMessage(Constants.MESSAGE_OK);
        }else {
            //否则返回错误状态码
            res.setCode(Constants.STATUS_FAIL);
            res.setMessage(Constants.MESSAGE_FAIL);
        }

        return res;
    }

    @PostMapping("/applyDel")
    public ResultResponse applyDel(@RequestHeader("authorization") String token,@RequestParam("applyId") String applyId){
        //System.out.println(token);
        ResultResponse res=new ResultResponse();
        //验证token的合法和有效性
        String tokenValue= JwtUtils.verify(token);
        System.out.println(tokenValue);
        if(tokenValue!=null && tokenValue.startsWith(JwtUtils.TOKEN_SUCCESS)){
            //如果合法则获取用户信息
            String userId=tokenValue.replaceFirst(JwtUtils.TOKEN_SUCCESS,"");

            //删除指定ID的相关申请信息
            commonService.delApply(applyId);
            res.setCode(Constants.STATUS_OK);
            res.setMessage(Constants.MESSAGE_OK);
        }else {
            //否则返回错误状态码
            res.setCode(Constants.STATUS_FAIL);
            res.setMessage(Constants.MESSAGE_FAIL);
        }
        return res;
    }
}
